<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import { RefreshLeft, Search } from "@element-plus/icons-vue";
import { ElForm } from "element-plus";
import { useRoute } from "vue-router";
import { getVppUserListAll } from "@/api/vppUser";
import moment from "moment";
import { getGainDayUser, getGainDayVpp } from "@/api/dayDetailedIncome";
import VChart from "@/views/monitor/server/components/VChart.vue";
import { dayRangeArray, timeSlot } from "@/utils";
const route = useRoute();
const activeUserId = ref(route.query?.id);
const activeName = ref("first");
const twoEchart = ref(null);
const allUser = reactive({
  data: []
});
const allVppUser = reactive({
  data: [
    {
      id: 1,
      name: "测试场站"
    }
  ]
});
const loading = ref(false);
const queryForm = reactive({
  data: {
    activeUserId: activeUserId.value,
    activeTime: []
  }
});
const queryFormTwo = reactive({
  data: {
    activeUserId: undefined,
    activeTime: []
  }
});
const showData = reactive({
  data: []
});
const showDataTwo = reactive({
  data: []
});
const optionsOne = ref({
  dataZoom: [
    {
      show: true,
      type: "inside",
      start: 0,
      end: 100
    },
    {
      show: true,
      type: "slider",
      start: 0,
      end: 100
    }
  ],
  tooltip: {
    show: true,
    trigger: "axis"
  },
  legend: {
    show: true
  },
  xAxis: {
    type: "category",
    axisLabel: {
      //x轴文字的配置
      show: true
      // interval: 0,//使x轴文字显示全
    },
    splitLine: {
      show: true,
      interval: (index, value) => {
        if (value.indexOf("00:00:00") > -1) {
          return true;
        } else {
          return false;
        }
      },
      lineStyle: {
        type: "solid",
        width: 1.3
      }
    },
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: "value",
    show: true,
    min: "dataMin",
    axisLine: {
      show: true // 显示Y轴线
    }
  },
  series: [
    {
      name: "每日分时用户收益",
      type: "line",
      showSymbol: false,
      smooth: true,
      data: []
    }
  ]
});
const optionsTwo = ref({
  dataZoom: [
    {
      show: true,
      type: "inside",
      start: 0,
      end: 100
    },
    {
      show: true,
      type: "slider",
      start: 0,
      end: 100
    }
  ],
  tooltip: {
    show: true,
    trigger: "axis"
  },
  legend: {
    show: true
  },
  xAxis: {
    type: "category",
    axisLabel: {
      //x轴文字的配置
      show: true
      // interval: 0,//使x轴文字显示全
    },
    splitLine: {
      show: true,
      interval: (index, value) => {
        if (value.indexOf("00:00:00") > -1) {
          return true;
        } else {
          return false;
        }
      },
      lineStyle: {
        type: "solid",
        width: 1.3
      }
    },
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: "value",
    show: true,
    min: "dataMin",
    axisLine: {
      show: true // 显示Y轴线
    }
  },
  series: [
    {
      name: "每日分时虚拟电厂收益",
      type: "line",
      showSymbol: false,
      smooth: true,
      data: []
    }
  ]
});
const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "最近一月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "最近三月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  }
];
const times = ref(timeSlot(15));
const keys = ref(
  Array(96)
    .fill(1)
    .map((_, index) => index + 1)
    .map(i => `p${i > 9 ? i : "0" + i}`)
);
const dataFormat = data => {
  let days = [];
  if (queryForm.data.activeTime && queryForm.data.activeTime.length) {
    days = dayRangeArray(
      queryForm.data.activeTime[0],
      queryForm.data.activeTime[1]
    );
  } else {
    days = [];
  }
  let allData = [];
  let xData = [];
  days.forEach(i => {
    let item = {};
    item.dataDate = i + " 00:00:00";
    keys.value.forEach(key => {
      item[key] = null;
    });
    item.dataType = 1;
    allData.push(item);
    let item2 = {};
    item2.dataDate = i + " 00:00:00";
    keys.value.forEach(key => {
      item2[key] = null;
    });
    item2.dataType = 2;
    allData.push(item2);
  });
  for (let i = 0; i < allData.length; i++) {
    for (let j = 0; j < data.length; j++) {
      if (
        allData[i].dataDate === data[j].dataDate &&
        allData[i].dataType === data[j].dataType
      ) {
        allData[i] = Object.assign({}, allData[i], data[j]);
      }
    }
  }
  const ret = {};
  allData.forEach(i => {
    ret[i.dataDate] = {
      "1": {},
      "2": {}
    };
  });
  allData.forEach(i => {
    ret[i.dataDate][i.dataType + ""] = i;
  });
  showData.data = [];
  let oneData = allData.filter(i => i.dataType === 1);
  let isd = [];
  oneData.forEach(i => {
    times.value.forEach((z, index) => {
      xData.push(i.dataDate.split(" ")[0] + " " + z + ":00");
      isd.push({
        value: i[keys.value[index]]
      });
      showData.data.push({
        label: i.dataDate.split(" ")[0] + " " + z + ":00",
        value: i[keys.value[index]]
      });
    });
  });
  let start = (1 - 96 / xData.length) * 100;
  optionsOne.value.xAxis.data = xData;
  optionsOne.value.dataZoom[0].start = start;
  optionsOne.value.dataZoom[1].start = start;
  optionsOne.value.series[0].data = isd;
};
const dataFormatTwo = data => {
  let days = [];
  if (queryForm.data.activeTime && queryForm.data.activeTime.length) {
    days = dayRangeArray(
      queryForm.data.activeTime[0],
      queryForm.data.activeTime[1]
    );
  } else {
    days = [];
  }
  let allData = [];
  let xData = [];
  days.forEach(i => {
    let item = {};
    item.dataDate = i + " 00:00:00";
    keys.value.forEach(key => {
      item[key] = null;
    });
    item.dataType = 1;
    allData.push(item);
    let item2 = {};
    item2.dataDate = i + " 00:00:00";
    keys.value.forEach(key => {
      item2[key] = null;
    });
    item2.dataType = 2;
    allData.push(item2);
  });
  for (let i = 0; i < allData.length; i++) {
    for (let j = 0; j < data.length; j++) {
      if (
        allData[i].dataDate === data[j].dataDate &&
        allData[i].dataType === data[j].dataType
      ) {
        allData[i] = Object.assign({}, allData[i], data[j]);
      }
    }
  }
  const ret = {};
  allData.forEach(i => {
    ret[i.dataDate] = {
      "1": {},
      "2": {}
    };
  });
  allData.forEach(i => {
    ret[i.dataDate][i.dataType + ""] = i;
  });

  let oneData = allData.filter(i => i.dataType === 1);
  let isd = [];
  showDataTwo.data = [];
  oneData.forEach(i => {
    times.value.forEach((z, index) => {
      xData.push(i.dataDate.split(" ")[0] + " " + z + ":00");
      isd.push({
        value: i[keys.value[index]]
      });
      showDataTwo.data.push({
        label: i.dataDate.split(" ")[0] + " " + z + ":00",
        value: i[keys.value[index]]
      });
    });
  });
  let start = (1 - 96 / xData.length) * 100;
  optionsTwo.value.xAxis.data = xData;
  optionsTwo.value.dataZoom[0].start = start;
  optionsTwo.value.dataZoom[1].start = start;
  optionsTwo.value.series[0].data = isd;
};
const init = async () => {
  let res = await getVppUserListAll();
  allUser.data = res.map(i => ({ ...i, id: i.id + "" }));
  queryForm.data.activeTime = [
    moment().subtract("day", 1).format("YYYY-MM-DD"),
    moment().format("YYYY-MM-DD")
  ];
  queryFormTwo.data.activeTime = [
    moment().subtract("day", 1).format("YYYY-MM-DD"),
    moment().format("YYYY-MM-DD")
  ];
  if (queryForm.data.activeUserId) {
    loading.value = true;
    let data = await getGainDayUser({
      vppUserId: queryForm.data.activeUserId,
      begin: queryForm.data.activeTime[0],
      end: queryForm.data.activeTime[1]
    });
    dataFormat(data);
    loading.value = false;
  } else {
    dataFormat([]);
  }
};
const search = async () => {
  if (
    queryForm.data.activeUserId &&
    queryForm.data.activeTime &&
    queryForm.data.activeTime.length
  ) {
    loading.value = true;
    let data = await getGainDayUser({
      vppUserId: queryForm.data.activeUserId,
      begin: queryForm.data.activeTime[0],
      end: queryForm.data.activeTime[1]
    });
    dataFormat(data);
    loading.value = false;
  } else {
    dataFormat([]);
  }
};
const SearchTwo = async () => {
  if (
    queryFormTwo.data.activeUserId &&
    queryFormTwo.data.activeTime &&
    queryFormTwo.data.activeTime.length
  ) {
    loading.value = true;
    let data = await getGainDayVpp({
      vppId: queryFormTwo.data.activeUserId,
      begin: queryFormTwo.data.activeTime[0],
      end: queryFormTwo.data.activeTime[1]
    });
    dataFormatTwo(data);
    loading.value = false;
  } else {
    dataFormatTwo([]);
  }
};

const resetQuery = () => {
  queryForm.data = {
    activeUserId: route.query?.id,
    activeTime: [
      moment().subtract("day", 1).format("YYYY-MM-DD"),
      moment().format("YYYY-MM-DD")
    ]
  };
};

const resetQueryTwo = () => {
  queryFormTwo.data = {
    activeUserId: undefined,
    activeTime: [
      moment().subtract("day", 1).format("YYYY-MM-DD"),
      moment().format("YYYY-MM-DD")
    ]
  };
};
const cactiveName = ref("first");
const c2activeName = ref("first");
const columns = [
  {
    key: "label",
    dataKey: "label",
    title: "时间",
    width: "50%"
  },
  {
    key: "value",
    dataKey: "value",
    title: "用户收益",
    width: "50%"
  }
];
const columns2 = [
  {
    key: "label",
    dataKey: "label",
    title: "时间",
    width: "50%"
  },
  {
    key: "value",
    dataKey: "value",
    title: "虚拟电厂收益",
    width: "50%"
  }
];
onMounted(() => {
  init();
});
const chartsLoading = ref(false);
</script>

<template>
  <div class="main h-[calc(100%-29px)]">
    <el-card v-loading="loading" class="w-full my-card-full">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="每日分时用户收益" name="first" />
        <el-tab-pane label="每日分时虚拟电厂收益" name="second" />
      </el-tabs>
      <div
        v-if="activeName === 'first'"
        key="1"
        class="one flex-1 flex flex-col"
      >
        <el-form :inline="true" :model="queryForm.data" label-width="0px">
          <el-form-item>
            <el-select
              v-model="queryForm.data.activeUserId"
              placeholder="选择用户"
              style="width: 240px"
            >
              <el-option
                v-for="item in allUser.data"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="queryForm.data.activeTime"
              unlink-panels
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
              date-format="YYYY-MM-DD"
              :shortcuts="shortcuts"
            />
          </el-form-item>
          <el-form-item class="ml-[10px]">
            <el-button type="primary" :icon="Search" @click="search"
              >查询</el-button
            >
            <el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-tabs v-model="cactiveName">
          <el-tab-pane label="图表" name="first" />
          <el-tab-pane label="列表" name="second" />
        </el-tabs>
        <div
          v-if="cactiveName === 'first'"
          v-loading="chartsLoading"
          style="width: 99%"
          class="flex-1"
        >
          <v-chart :options="optionsOne" />
        </div>
        <div
          v-if="cactiveName === 'second'"
          v-loading="chartsLoading"
          style="width: 99%"
          class="flex-1"
        >
          <el-table-v2
            :columns="columns"
            :data="showData.data"
            :width="1614"
            :height="600"
            :scrollbar-always-on="false"
          />
        </div>
      </div>
      <div
        v-if="activeName === 'second'"
        key="2"
        class="two flex-1 flex flex-col"
      >
        <el-form :inline="true" :model="queryFormTwo.data" label-width="0px">
          <el-form-item>
            <el-select
              v-model="queryFormTwo.data.activeUserId"
              placeholder="选择用户"
              style="width: 240px"
            >
              <el-option
                v-for="item in allVppUser.data"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="queryFormTwo.data.activeTime"
              unlink-panels
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
              date-format="YYYY-MM-DD"
              :shortcuts="shortcuts"
            />
          </el-form-item>
          <el-form-item class="ml-[10px]">
            <el-button type="primary" :icon="Search" @click="SearchTwo"
              >查询</el-button
            >
            <el-button :icon="RefreshLeft" @click="resetQueryTwo"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-tabs v-model="c2activeName">
          <el-tab-pane label="图表" name="first" />
          <el-tab-pane label="列表" name="second" />
        </el-tabs>
        <div
          v-if="c2activeName === 'first'"
          v-loading="chartsLoading"
          style="width: 99%"
          class="flex-1"
        >
          <v-chart ref="twoEchart" :options="optionsTwo" />
        </div>
        <div
          v-if="c2activeName === 'second'"
          v-loading="chartsLoading"
          style="width: 99%"
          class="flex-1"
        >
          <el-table-v2
            :columns="columns2"
            :data="showDataTwo.data"
            :width="1614"
            :height="600"
            :scrollbar-always-on="false"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.my-card-full {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
  }
}
</style>
